﻿using System;
using System.Data;
using System.Runtime.InteropServices;
using System.Web.UI.WebControls;
using WebShopData;

namespace Projekt_2_ASP.NET
{
    public partial class Main : System.Web.UI.Page
    {
        private DataSet _set;
        private const string CURRENCY = "SEK";
        protected void Page_Load(object sender, EventArgs e)
        {
            this.Title = "Hem";
            _set = WebShopDal.GetAllArticles();
            GridViewProducts.DataSource = _set;
            GridViewProducts.DataBind();
            foreach (TableRow row in GridViewProducts.Rows)
                row.Cells[2].Text = string.Format(
                        "{0} {1}", row.Cells[2].Text.Substring(0, row.Cells[2].Text.Length - 2), CURRENCY);

        }

        protected void GridViewProducts_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            bool CorrectButtonClick = e.CommandName == "Buy";
            if (CorrectButtonClick == false)
                return;

            int articleID = int.Parse(_set.Tables[0].Rows[int.Parse(e.CommandArgument.ToString())]["ArticleID"].ToString());
            

            bool foundOrderRow = false;
            var sessionOrder = (Session["Order"] as Order);
            int rowsInSessionOrder = sessionOrder.OrderRows.Count;
            for (int i = 0; i < rowsInSessionOrder; i++)
            {
                bool articleIDMatch = sessionOrder.OrderRows[i].ArticleID == articleID;
                if (articleIDMatch)
                {
                    (Session["Order"] as Order).OrderRows[i].Quantity++;
                    sessionOrder = (Order)Session["Order"];
                    foundOrderRow = true;
                }
            }

            if (foundOrderRow == false)
                (Session["Order"] as Order).OrderRows.Add(new OrderRow(articleID, 1));
            Response.Redirect("~/Main.aspx");
        }
    }


}